import numpy as np
import time
from multiprocessing import Process
import serial
from ParseBuffer import *
from Parameter import *


class RecvProcess(Process):
    def __init__(self, outQ):
        Process.__init__(self)
        self.outQ = outQ

    def run(self):
        rx_com(self.outQ)


def rx_com(rxQ):
    ser = serial.Serial()
    ser.baudrate = BaudRate
    ser.timeout = 2
    if ser.is_open:
        ser.close()

    for n in range(256):
        port_name = 'COM' + str(n)
        ser.port = port_name
        try:
            ser.open()
            if ser.is_open:
                break
        except:
            pass
    if not ser.is_open:
        print("**ERROR**: COM port open FAIL.")
        return

    if ser.is_open:
        print("USB COM port open success.")
        time.sleep(0.1)
        ser.reset_input_buffer()

        try:
            while True:
                TempBuffer = ser.read(FrameBytesCount)
                pTempBuffer = np.frombuffer(TempBuffer, dtype=np.uint8)
                chirps = parse_buffer(pTempBuffer)
                rxQ.put(chirps)
        except:
            print("Error receiving data.")
